package com.Input;

import java.io.IOException;
import java.util.*;

import com.pi4j.io.i2c.I2CBus;
import com.pi4j.io.i2c.I2CDevice;
import com.pi4j.io.i2c.I2CFactory;

public class PhInput implements Runnable {

	double pH = 7;
	double[] pHData = new double[50];
	
	int pHDataIndex = 0;

	public double getPh() {
		return pH;
	}
	
	@Override
	public void run() {

		System.out.println(" ... PH THREAD STARTED ...");
		System.out.println(" ... COMMUNICATING VIA I2C ...");
		
		for(int i=0;i<50;i++){
			pHData[i] = 7;
		}

		I2CBus i2cBus;
		try {
			i2cBus = I2CFactory.getInstance(I2CBus.BUS_1);

			// create I2C bus
			I2CDevice pHSensor = i2cBus.getDevice(0x4D); // create pHSensor I2C
															// device

			byte[] buffer = new byte[2]; // create buffer for sensor ADC
											// readings (two bytes)

			while (true) {
				Thread.sleep(100);
				int amountBytes = pHSensor.read(buffer, 0, 2); // read two
																// bytes, store
																// them in
																// buffer
	//			System.out.println("Number of bytes read : " + amountBytes);
				/*
				 * for(byte b : buffer) { System.out.println("Data : "+ b
				 * +" hex 0x"+Integer.toHexString((b & 0xff))); }
				 */
				int ADC = buffer[0] * 256 + buffer[1];
				double pHRead = 0.002612*ADC + 1.576;
				pHData[pHDataIndex]=pHRead;
				pHDataIndex++;
				if(pHDataIndex>49){
					pHDataIndex=0;
				}
				double pHSum =0;
				for(int i=0;i<50;i++){
					pHSum = pHSum+pHData[i];
				}
				pH = pHSum/50;
				//System.out.println("          pH: " + pH);

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
